package com.sjzd.server.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sjzd.server.constant.MailConstants;
import com.sjzd.server.pojo.Employee;
import com.sjzd.server.pojo.MailLog;
import com.sjzd.server.service.IEmployeeService;
import com.sjzd.server.service.IMailLogService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
public class MailTask {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private IMailLogService mailLogService;
    @Autowired
    private IEmployeeService employeeService;

    /**
     *  邮件发送定时任务
     *  10秒一次
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void schedule() {
        QueryWrapper<MailLog> queryWrapper = new QueryWrapper<MailLog>().eq("status", MailConstants.DELIVERING)
                .lt("tryTime", LocalDateTime.now());
        List<MailLog> mailLogs = mailLogService.list(queryWrapper);
        if (mailLogs != null && !mailLogs.isEmpty()) {
            for (final MailLog mailLog : mailLogs) {
                UpdateWrapper<MailLog> updateWrapper = null;
                if (mailLog.getCount() < MailConstants.MAX_RETRY_COUNT) {
                    Employee employee = employeeService.getEmployee(mailLog.getEid()).get(0);
                    rabbitTemplate.convertAndSend(MailConstants.EXCHANGE_NAME, MailConstants.ROUTER_KEY, employee,
                            new CorrelationData(mailLog.getMsgId()));
                    updateWrapper = new UpdateWrapper<MailLog>().set("count", mailLog.getCount() + 1).set("tryTime", LocalDateTime.now())
                            .eq("msgId", mailLog.getMsgId());
                } else {
                   updateWrapper = new UpdateWrapper<MailLog>().set("status", MailConstants.ERROR_SEND)
                            .eq("msgId", mailLog.getMsgId());
                }
                mailLogService.update(updateWrapper);
            }
        }

    }

}
